package light.head.controller.inv;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Url;
import light.head.dao.inv.InvBusinessContactsDAO;
import light.head.dao.inv.InvBusinessDAO;
import light.head.dao.inv.InvBusinessTypeDAO;
import light.head.dao.sys.OrganDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.Organ;
import light.head.model.inv.InvBusiness;
import light.head.model.inv.InvBusinessContacts;
import light.head.model.inv.InvBusinessType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = Url.C_INVBUSINESS)
public class InvBusinessController extends SupporterController{
	
	private InvBusinessDAO ibDAO;
	private InvBusinessTypeDAO ibtDAO;
	private InvBusinessContactsDAO ibcDAO;
	private OrganDAO organDAO;
	
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.INVBUSINESS_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME,Parm.CN, Parm.DELETED, Parm.ON, Parm.TYPE,"sid","stn");
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (ibDAO.findByMap(oc, map, pb) == RESULT.SUCCESS){
			InvBusiness ib =null;
			for (Object o : pb.getResultList()) {
				ib = (InvBusiness) o;
				ib.setItemList(ibcDAO.findIsc(ib.getCode()));
			}
		}
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.INVBUSINESS_LIST);
	}

	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			InvBusiness ib = ibDAO.get(Integer.parseInt(code));
			if (null != ib) {
				List<InvBusinessContacts> list = ibcDAO.findIsc(Integer.parseInt(code));
				ib.setItemList(list);
				request.setAttribute(Parm.INVBUSINESS, ib);
			}
		}
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		List<InvBusinessType> typeList = ibtDAO.findAll(oc);
		if (null != typeList && typeList.size() > 0) {
			StringBuffer result = new StringBuffer("[");
			for (InvBusinessType type : typeList){
				result.append("{");
				result.append("\"stn\":\"" + type.getName() +"\",");
				result.append("\"stc\":\"" + type.getCode() +"\"");
				result.append("},");
			}
			result.deleteCharAt(result.length() - 1).append("]");
			request.setAttribute(Parm.TYPE, result.toString());
		} 
		return new ModelAndView(Url.INVBUSINESS_EDIT);
	}
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			InvBusiness ib = ibDAO.get(Integer.parseInt(code));
			if (null != ib) {
				List<InvBusinessContacts> list = ibcDAO.findIsc(Integer.parseInt(code));
				ib.setItemList(list);
				request.setAttribute(Parm.INVBUSINESS, ib);
			}
		}
		return new ModelAndView(Url.INVBUSINESS_EDIT);
	}
	@RequestMapping(value = Url.SAVE)
	public void save(InvBusiness ib, HttpServletRequest request, HttpServletResponse response) throws Exception{
		RESULT result = RESULT.ERROR;
		if (ib == null) {
			print(response, Msg.PARAMETER_ERROR);
			return ;
		}
		
		
		// 检查是否有可以保存的明细在保存,至少有一条明细可以保存
		boolean ok = true;
		for (InvBusinessContacts Item : ib.getItemList()) {
			if (null != Item && null != Item.getName() && null != Item.getPhone() && Item.getQq() != null ) {
				ok = false;
			}
		}
		if (ok) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if(ib.getStn() == null || ib.getStn() == ""){
			print(response, Msg.EXISTS);
			return;
		}
		if (ib.getCode() == null ) {
			List<InvBusinessType> isc = ibtDAO.findByNameOc(ib.getStn(), oc);
			if (isc == null || isc.size() == 0)  {
				InvBusinessType ibt = new InvBusinessType();
				ibt.setName(ib.getStn());
				ibt.setCt(new Date());
				ibt.setDeleted(false);
				ibt.setOc(oc);
				ibt.setCu(cu_code(request));
				ibtDAO.add(ibt);
				ib.setStc(ibt.getCode());
			}else{
				ib.setStc(isc.get(0).getCode());
			}
			ib.setCu(cu_code(request));
			ib.setCt(new Date());
			ib.setOc(oc);
			result = ibDAO.add(ib);
		} else {
			List<InvBusinessType> isc = ibtDAO.findByNameOc(ib.getStn(), oc);
			if (isc == null || isc.size() == 0)  {
				InvBusinessType ibt = new InvBusinessType();
				ibt.setName(ib.getStn());
				ibt.setCt(new Date());
				ibt.setDeleted(false);
				ibt.setOc(oc);
				ibt.setCu(cu_code(request));
				ibtDAO.add(ibt);
				ib.setStc(ibt.getCode());
			}else{
				ib.setStc(isc.get(0).getCode());
			}
			result = ibDAO.update(ib);
		}
		if (RESULT.SUCCESS == result && ib.getItemList().size() > 0) {
			List<InvBusinessContacts> list = ib.getItemList();						//页面上传过来的联系人
			List<InvBusinessContacts> oldList = ibcDAO.findIsc(ib.getCode());		//数据库里的联系人
			List<InvBusinessContacts> deletedList = new ArrayList<InvBusinessContacts>();	// 存放页面已经删除的角色节点
			Boolean yes = null;
			for (InvBusinessContacts db : oldList) {
				yes = true;
				if (ib.getItemList() == null || ib.getItemList().size() == 0) {
					deletedList.add(db);
				} else {
					for (InvBusinessContacts ibc : list) {
						if (null != ibc.getCode() && ibc.getCode().intValue() == db.getCode().intValue()) {
							yes = false;
							break;
						} 
					}
					if (yes) {
						deletedList.add(db);
					}
				}
			}
			// 删除(在数据库中deleted = true)
			for (InvBusinessContacts ua : deletedList) {
				ua.setDeleted(true);
				result = ibDAO.upd(ua);
				if (RESULT.SUCCESS != result) {
					throw new Exception("保存失败"); 
				}
			}
			for (InvBusinessContacts pii : list) {
				if (null == pii.getCode()) {
					if (null != pii.getName() && null != pii.getPhone() && pii.getQq() != null ) {
						pii.setIsc(ib.getCode());
						pii.setCt(new Date());
						pii.setCu(cu_code(request));
						pii.setOc(oc);
						result = ibDAO.add(pii);
					}
				} else {
					for (InvBusinessContacts old : oldList) {
						if (pii.getCode().intValue() == old.getCode().intValue()) {
							old.setPhone(pii.getPhone());
							old.setName(pii.getName());
							old.setQq(pii.getQq());
							old.setDc(pii.getDc());
							result = ibDAO.upd(old);
						}
					}
				}
			}
			
			print(response, Msg.SUCCESS);
		} else
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.SHIELD)
	public void shield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		InvBusiness ib = ibDAO.get(Integer.parseInt(code));
		if (null == ib) {
			print(response, Msg.NOT_FIND);
			return;
		}
		ib.setDeleted(true);
		if (ibDAO.upd(ib) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.UN_SHIELD)
	public void unshield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		InvBusiness ib = ibDAO.get(Integer.parseInt(code));
		if (null == ib) {
			print(response, Msg.NOT_FIND);
			return;
		}
		ib.setDeleted(false);
		if (ibDAO.upd(ib) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Integer code = cu_organCode(request);
 		if (null != code) {
 			List<Organ> list = organDAO.getAll();
			Organ o = findOgranByCode(code, list);
			if (null != o) {
				StringBuffer tree = new StringBuffer();
				if (!o.getDeleted()) {
					tree.append("p.add('" + o.getCode() + "','-1','"+ o.getName() + "');");
					aidTree(tree, o.getSonList());
				}
			
			request.setAttribute(Parm.TREE, tree);
			request.setAttribute(Parm.ORGAN, list);
			}
 		}
 		request.setAttribute(Parm.ID, request.getParameter(Parm.ID));
		request.setAttribute(Parm.NAME, request.getParameter(Parm.NAME));
		return new ModelAndView(Url.INVBUSINESS_AID_INIT);
	}
	
	private Organ findOgranByCode(Integer code, List<Organ> list){
		if(null != code && null != list && 0 < list.size()){
			for (Organ o : list){
				if(code.intValue() == o.getCode().intValue()){
					return o;
				} else {
					Organ or = findOgranByCode(code, o.getSonList());
					if (or != null) {
						return or;
					}
				}
			}
		}
		return null;
	}
	
	private void aidTree(StringBuffer tree, List<Organ> list) {
		if (null == tree || null == list || list.size() == 0)
			return;
		for (Organ o : list) {
			tree.append("p.add('" + o.getCode() + "','" + o.getPc() + "','" + o.getName() + "');");
			aidTree(tree, o.getSonList());
		}
	}

	
	/**
	 * 查询商品
	 */
	@RequestMapping(Url.AID_INIT_1)
	public ModelAndView aidInit1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.INVBUSINESS_INVBUSINESSTYPE_INIT);
	}

	@RequestMapping(Url.AID_LIST_1)
	public ModelAndView aidList1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME,Parm.ENAME,Parm.OC,Parm.GTN);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		ibtDAO.findByMap(organDAO.getSonCodeList(oc), map, pageBean);
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		return new ModelAndView(Url.INVBUSINESS_INVBUSINESSTYPE_LIST);
	}
	
	@Autowired
	public void setIbtDAO(InvBusinessTypeDAO ibtDAO) {
		this.ibtDAO = ibtDAO;
	}
	@Autowired
	public void setIbDAO(InvBusinessDAO ibDAO) {
		this.ibDAO = ibDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setIbcDAO(InvBusinessContactsDAO ibcDAO) {
		this.ibcDAO = ibcDAO;
	}

}
